home *** CD-ROM | disk | FTP | other *** search
/ Megaware 1 / Megaware Volume 1.iso / programg / c-tutor / chap03.txt < prev    next >
Text File  |  1990-07-20  |  14KB  |  294 lines

  1.  
  2.  
  3.  
  4.                                                         Chapter 3
  5.                                                          POINTERS
  6.  
  7. Because pointers are so important in C and C++, this chapter will
  8. review some of the more important topics concerning pointers.  Even
  9. if you are extremely conversant in the use of pointers, you should
  10. not completely ignore this chapter because some new material is
  11. presented here.
  12.  
  13.  
  14. POINTER REVIEW
  15. _________________________________________________________________
  16.  
  17. Examine the program named POINTERS.CPP for a     ================
  18. simple example of the use of pointers.  This is    POINTERS.CPP
  19. a pointer review and if you are comfortable with ================
  20. the use of pointers, you can skip this example
  21. program completely. 
  22. A pointer in either ANSI-C or C++ is declared with an asterisk
  23. preceding the variable name.  The pointer is then a pointer to a
  24. variable of that one specific type and should not be used with
  25. variables of other types.  Thus pt_int is a pointer to an integer
  26. type variable and should not be used with any other type.  Of
  27. course, an experienced C programmer knows that it is simple to
  28. coerce the pointer to be used with some other type by using a cast,
  29. but he must assume the responsibility for its correct usage.
  30.  
  31. In line 12 the pointer named pt_int is assigned the address of the
  32. variable named pig and line 13 uses the pointer named pt_int to add
  33. the value of dog to the value of pig because the asterisk
  34. dereferences the pointer in exactly the same manner as standard C. 
  35. The address is used to print out the value of the variable pig in
  36. line 14 illustrating the use of a pointer with the stream output
  37. operator cout.  Likewise, the pointer to float named pt_float is
  38. assigned the address of x, then used in a trivial calculation in
  39. line 18.
  40.  
  41. If you are not completely comfortable with this trivial program
  42. using pointers, you should review the use of pointers in any good
  43. C programming book or Coronado Enterprises C tutorial before
  44. proceeding on because we will assume that you have a thorough
  45. knowledge of pointers throughout the remainder of this tutorial. 
  46. It is not possible to write a C program of any significant size or
  47. complexity without the use of pointers.
  48.  
  49.  
  50. CONSTANT POINTERS AND POINTERS TO CONSTANTS
  51. _________________________________________________________________
  52.  
  53. The definition of C++ allows a pointer to a constant to be defined
  54. such that the value to which the pointer points cannot be changed
  55. but the pointer itself can be moved to another variable or
  56. constant.  The method of defining a pointer to a constant is
  57.  
  58.                                                          Page 3-1
  59.  
  60.                                              Chapter 3 - Pointers
  61.  
  62. illustrated in line 22.  In addition to a pointer to a constant,
  63. you can also declare a constant pointer, one that cannot be
  64. changed.  Line 23 illustrates this.  Note that neither of these
  65. pointers are used in illustrative code.
  66.  
  67. Either of these constructs can be used to provide additional
  68. compile time checking and improve the quality of your code.  If you
  69. know a pointer will never be moved due to its nature, you should
  70. define it as a constant pointer.  If you know that a value will not
  71. be changed, it can be defined as a constant and the compiler will
  72. tell you if you ever inadvertently attempt to change it.
  73.  
  74.  
  75. A POINTER TO VOID
  76. _________________________________________________________________
  77.  
  78. The pointer to void is actually a part of the ANSI-C standard but
  79. is relatively new so it is commented upon here.  A pointer to void
  80. can be assigned the value of any other pointer type.  You will
  81. notice that the pointer to void named general is assigned an
  82. address of an int type in line 15 and the address of a float type
  83. in line 20 with no cast and no complaints from the compiler.  This
  84. is a relatively new concept in C and C++.  It allows a programmer
  85. to define a pointer that can be used to point to many different
  86. kinds of things to transfer information around within a program. 
  87. A good example is the malloc() function which returns a pointer to
  88. void.  This pointer can be assigned to point to any entity, thus
  89. transferring the returned pointer to the correct type.
  90.  
  91. A pointer to void is aligned in memory in such a way that it can
  92. be used with any of the simple predefined types available in C++,
  93. or in ANSI-C for that matter.  They will also align with any
  94. compound types the user can define since compound types are
  95. composed of the simpler types.
  96.  
  97. Be sure to compile and execute this program.
  98.  
  99.  
  100. DYNAMIC ALLOCATION AND DEALLOCATION
  101. _________________________________________________________________
  102.  
  103. Examine the program named NEWDEL.CPP for our     ================
  104. first example of the new and delete operators.      NEWDEL.CPP
  105. The new and delete operators do dynamic          ================
  106. allocation and deallocation in much the same
  107. manner that malloc() and free() do in your old
  108. favorite C implementation.
  109.  
  110. During the design of C++, it was felt that since dynamic allocation
  111. and deallocation are such a heavily used part of the C programming
  112. language, it should be a part of the language, rather than a
  113. library add-on.  The new and delete operators are actually a part
  114. of the C++ language and are operators, much like the addition
  115. operator or the assignment operator.  They are therefore very
  116.  
  117.                                                          Page 3-2
  118.  
  119.                                              Chapter 3 - Pointers
  120.  
  121. efficient, and are very easy to use as we will see in this example
  122. program.
  123.  
  124. Lines 14 and 15 illustrate the use of pointers in the tradition of
  125. C and line 16 illustrates the use of the new operator.  This
  126. operator requires one modifier which must be a type as illustrated
  127. here.  The pointer named point2 is now pointing at the new integer
  128. variable which exists on the heap, and can be used in the same way
  129. that any dynamically allocated variable is used in ANSI-C.  Line
  130. 18 illustrates displaying the value on the monitor which was
  131. assigned in line 17.
  132.  
  133. Line 20 allocates another new variable and line 21 causes point2
  134. to refer to the same dynamically allocated variable as point1 is
  135. pointing to.  In this case, the reference to the variable that
  136. point2 was previously pointing to has been lost and it can never
  137. be used or deallocated.  It is lost on the heap until we return to
  138. the operating system when it will be reclaimed for further use, so
  139. this is obviously not good practice.  Note that point1 is
  140. deallocated with the delete operator in line 25, and point2 can not
  141. actually be deleted.  Since the pointer point1 itself is not
  142. changed, it is actually still pointing to the original data on the
  143. heap.  This data could probably be referred to again using point1,
  144. but it would be terrible programming practice since you have no
  145. guarantee what the system will do with the pointer or the data. 
  146. The data storage is returned to the free list to be allocated in
  147. a subsequent call, and will soon be reused in any practical
  148. program.
  149.  
  150. Since the delete operator is defined to do nothing if it is passed
  151. a NULL value, it is legal to ask the system to delete the data
  152. pointed to by a pointer with the value of NULL, but nothing will
  153. actually happen.  It is considered a no-op and is actually wasted
  154. code.  The delete operator can only be used to delete data
  155. allocated by a new operator.  If the delete is used with any other
  156. kind of data, the operation is undefined and anything can happen. 
  157. According to the ANSI standard, even a system crash is a legal
  158. result of this illegal operation, and can be defined as such by the
  159. compiler writer.
  160.  
  161. In line 27, we declare some floating point variables.  You will
  162. remember that in C++ the variables do not have to be declared at
  163. the beginning of a block.  A declaration is an executable statement
  164. and can therefore appear anywhere in a list of executable
  165. statements.  One of the float variables is allocated within the
  166. declaration to illustrate that this can be done.  Some of the same
  167. operations are performed on these float type variables as were done
  168. on the int types earlier.
  169.  
  170. Some examples of the use of a structure are given in lines 35
  171. through 41 and should be self explanatory.
  172.  
  173. Finally, since the new operator requires a type to determine the
  174. size of the dynamically allocated block, you may wonder how you can
  175.  
  176.                                                          Page 3-3
  177.  
  178.                                              Chapter 3 - Pointers
  179.  
  180. allocate a block of arbitrary size.  This is possible by using the
  181. construct illustrated in line 47 where a block of 37 char sized
  182. entities, which will be 37 bytes, is allocated.  A block of 133
  183. bytes greater than the size of the date structure is allocated in
  184. line 49.  It is therefore clear that the new operator can be used
  185. with all of the flexibility of the malloc() function which you are
  186. used to using.
  187.  
  188. The standard functions which you have been using in C for dynamic
  189. memory management, malloc(), calloc(), and free(), are also
  190. available for use in C++ and can be used in the same manner they
  191. were used in C.  The new and delete operators should not be
  192. intermixed with the older function calls since the results may be
  193. unpredictable.  If you are updating code with the older function
  194. calls, continue to use them for any additions to the code.  If you
  195. are designing and coding a new program you should use the newer
  196. constructs because they are a built in part of the language rather
  197. than an add on and are therefore more efficient.
  198.  
  199. Be sure to compile and execute this program.
  200.  
  201.  
  202. POINTERS TO FUNCTIONS
  203. _________________________________________________________________
  204.  
  205. Examine the program named FUNCPNT.CPP for an      ===============
  206. example of using a pointer to a function.  It       FUNCPNT.CPP
  207. must be pointed out that there is nothing new     ===============
  208. here, the pointer to a function is available in
  209. ANSI-C as well as in C++ and works in the manner
  210. described here for both languages.  It is not regularly used by
  211. most C programmers, so it is defined here for your information.
  212.  
  213. There is nothing unusual about this program except for the pointer
  214. to a function declared in line 8.  This declares a pointer to a
  215. function which returns nothing (void) and requires a single formal
  216. parameter, a float type variable.  You will notice that all three
  217. of the functions declared in lines 5 through 7 fit this profile and
  218. are therefore candidates to be called with this pointer.  If you
  219. have not used prototyping in C, these lines will look strange to
  220. you.  Don't worry about them at this point since we will study
  221. prototyping in the next chapter of this tutorial.
  222.  
  223. Observe that in line 15 we call the function print_stuff() with the
  224. parameter pi and in line 16 we assign the function pointer named
  225. function_pointer the value of print_stuff() and use the function
  226. pointer to call the same function again in line 17.  Lines 15 and
  227. 17 are therefore identical in what is accomplished because of the
  228. pointer assignment in line 16.  In lines 18 through 23, a few more
  229. illustrations of the use of the function pointer are given.  You
  230. will be left to study these on your own.
  231.  
  232. Since we assigned the name of a function to a function pointer, and
  233. did not get an assignment error, the name of a function must be a
  234.  
  235.                                                          Page 3-4
  236.  
  237.                                              Chapter 3 - Pointers
  238.  
  239. pointer to that function.  This is exactly the case, a function
  240. name is a pointer to that function, but it is a pointer constant
  241. and cannot be changed.  This is exactly the case we found when we
  242. studied arrays in ANSI-C at some point in our C programming
  243. background.  An array name is a pointer constant to the first
  244. element of the array.
  245.  
  246. Since the name of the function is a constant pointer to that
  247. function, we can assign the name of the function to a function
  248. pointer and use the function pointer to call the function.  The
  249. only caveat is that the return value and the number and types of
  250. parameters must be identical.  Most C and C++ compilers will not,
  251. and in fact, can not warn you of type mismatches between the
  252. parameter lists when the assignments are made.  This is because the
  253. assignments are done at runtime when no type information is
  254. available to the system, rather than at compile time when all type
  255. information is available.
  256.  
  257. This use and operations of pointers must be thoroughly understood
  258. when we get to the material on dynamic binding and polymorphism
  259. later in this tutorial.  It will be discussed in detail at that
  260. time.
  261.  
  262. Be sure to compile and execute this program.
  263.  
  264.  
  265. PROGRAMMING EXERCISES
  266. _________________________________________________________________
  267.  
  268.  
  269. 1.   When dynamically allocated data is deleted, it is still
  270.      actually in memory, stored on the heap.  Repeat the output
  271.      statement from line 23 of NEWDEL.CPP immediately following the
  272.      delete in line 25 to see if the values are really still there. 
  273.      Repeat it once again just prior to the end of the program when
  274.      the data spaces should have been written over to see if you
  275.      get garbage out.  Even if your compiler reports the correct
  276.      data, it is terrible practice to count on this data still
  277.      being there because in a large dynamic program, the heap space
  278.      will be used repeatedly.
  279.  
  280. 2.   Add a function to FUNCPNT.CPP which uses a single integer for
  281.      a parameter and attempt to call it by using the function
  282.      pointer to see if you get the correct data into the function.
  283.  
  284.  
  285.  
  286.  
  287.  
  288.  
  289.  
  290.  
  291.  
  292.  
  293.                                                          Page 3-5
  294.